package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class ApUnlikesBehaviorServiceImpl implements IApUnlikesBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public ResponseResult saveUnlikes(UnLikesBehaviorDto dto) {
//       构建 一个不喜欢雷
        ApUnlikesBehavior unlikesBehavior=new ApUnlikesBehavior();
//        获得线程id
        User user = AppThreadLocalUtil.get();
        if(user!=null){
            unlikesBehavior.setUserId(user.getUserId());

        }else {
            unlikesBehavior.setEquipmentId(dto.getEquipmentId());
        }
        unlikesBehavior.setArticleId(dto.getArticleId());
        unlikesBehavior.setType(dto.getType());
        unlikesBehavior.setCreatedTime(new Date());
//       查找不喜欢记录
        Query query=new Query();
        query.addCriteria(Criteria.where("articleId").is(unlikesBehavior.getArticleId()));
        if(user!=null){
            query.addCriteria(Criteria.where("userId").is(unlikesBehavior.getUserId()));

        }else {
            query.addCriteria(Criteria.where("equipmentId").is(unlikesBehavior.getEquipmentId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
//        判断记录会有
        if(one==null){
            mongoTemplate.save(unlikesBehavior);


        }else {
//
            if (one.getType()!=dto.getType()){
                one.setType(dto.getType());
                mongoTemplate.save(one);

            }

        }


        return ResponseResult.okResult();
    }
//获得不喜欢的
    @Override
    public ResponseResult<ApUnlikesBehavior> getUnlikes(UnLikesBehaviorDto dto) {


        Query query=new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if(dto.getUserId()!=null){
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));

        }else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        return ResponseResult.okResult(one);
    }

}
